var dialogClass = 'medhub_dialog';

/*
 * Use for load partial page content
 * @param strUrl : Url request to servlet
 * @param strContent : content to be placed normally use class name
 */

function loadAjaxContent(strUrl, strContent) {
    $(strContent).html('<div class="content-box" style="text-align: center;"><img src="' + rootPath + '/images/loading.gif" /></div>');
    $(strContent).load(rootPath+strUrl, "",
    function (responseText, textStatus, XMLHttpRequest) {
        if (textStatus == "success") {
            // all good!
        }
        if (textStatus == "error") {
            // oh noes!
            alert("Page Not Found");
        }
    }
);
}

function loadAjaxPage(strUrl, strContent) {
    /**
     * Clear Dialog When Change Page
     * !!Rule : Dialog must have class "medhub_dialog"
     */
    $(".ui-dialog").dialog("destroy");
    $(".medhub_dialog").remove();
    $(document).validationEngine('hideAll');

    /**
     * End Clear Dialog When Change Page
     */
    
    $(strContent).html('<div class="content-box" style="text-align: center;"><img src="' + rootPath + '/images/loading.gif" /></div>');
    $(strContent).load(rootPath+strUrl, "",
    function (responseText, textStatus, XMLHttpRequest) {
        if (textStatus == "success") {
            // all good!
        }
        if (textStatus == "error") {
            // oh noes!
            alert("Page Not Found");
        }
    }
);
}

/*
 * Use when Redirect by Header Menu
 */
function loadAjaxContentByHeaderMenu (strUrl, strSelector, obj) {
    loadAjaxPage(strUrl, strSelector);
    $(".sf-menu .current").removeClass("current");
    $(obj).addClass("current");
}

/*
 * Use when access denied and want to show for login first
 */
function showLogin() {
    $("#toppanel #panel").slideDown("slow");
    $("#toppanel #open").hide();
    $("#toppanel #close").show();
    // @TODO : Clear user Log out
}

/*
 * Update jQuery Plugin Control
 */
function updateForm() {
    //var jCurrent = jQuery.noConflict();
    $(".chzn-select").trigger("liszt:updated");
    $(document).find("button").button( 'refresh' );
    $(document).validationEngine('hideAll');

    if ($.uniform.elements.length > 0) {
        $.uniform.update();
    }

}

/*
 * Check String
 */
function isEmpty(str) {
    return (!str || 0 === str.length || str === "null" || str === "undefined"); //null is value from servlet
}

function initFileUpload (pageObj, suffix) {
    pageObj.find("#"+suffix).fileupload({
        namespace: 'file_upload_' + suffix,
        uploadTable: $('#files_' + suffix),
        downloadTable: $('#files_' + suffix),
        buildUploadRow: function (files, index) {
            return $('<tr><td>' + files[index].name + '<\/td>' +
                '<td class="file_upload_progress"><div><\/div><\/td>' +
                '<td class="file_upload_cancel">' +
                '<button class="ui-state-default ui-corner-all" title="Cancel">' +
                '<span class="ui-icon ui-icon-cancel">Cancel<\/span>' +
                '<\/button><\/td><\/tr>');
        },
        buildDownloadRow: function (file) {
            return $('<tr><td>' + file.name + '<\/td><\/tr>');
        }
    });
}

function populateSelect(el, items ,strDefault, idSelected) {
    if (el==null)return false;
    var index=0;
    el.options.length = 0;
    if (items.length > 0)
        el.options[0] = new Option(strDefault, '');
    $.each(items, function () {
        el.options[el.options.length] = new Option(this.name, this.value);
        if (this.value==idSelected) // use id value for option selected
            index=el.options.length-1;
    });
    if (idSelected==""){
        el.options[0].selected = true; // set strDefault for selected
    }else{
        el.options[index].selected = true; // set index from value for selected
    }

    return true;
}

/*
 * Switch Div Content with slide effect
 *
 */
function switchContent(idContent, idWrapper) {
    idWrapper.children().hide('fast',loadContent);
    //idWrapper.find("#load").remove();
    //idContent.append('<span id="load">LOADING...</span>');
    //idWrapper.find("#load").fadeIn('normal');
    function loadContent() {
        showNewContent();
    }
    function showNewContent() {
        if (!idWrapper.children().is(":visible")) {
            idContent.show('normal',hideLoader());
        }
			
    }
    function hideLoader() {
        //idWrapper.find("#load").fadeOut('normal');
    }
}
function hideContent(idWrapper) {
    idWrapper.children().hide('fast');

}

/*
 * Jquery Tabs Function
 */
function validateTabs(tabsObj) {
    var countInvalid = 0;
    tabsObj.find(".ui-tabs-hide").each(function(index){ //Find Tab that not selected
        var tabElement = $(this); //Must declare this to jquery obj for call validateTab function
        var tabIdName = this.getAttribute("id");
        var tabIndex = getTabIndexById(tabsObj, tabIdName); //Get this's Tab index

        if (!tabElement.validateTab(tabsObj, tabIndex)) { //Validate element in Tab that not select ? Valid : Invalid
            //Invalid for this tab
            tabsObj.find("#hpl-" + tabIdName).validationEngine('showPrompt', 'This field is required.', '');
            countInvalid++;
            return false; //Break each loop
        }
    });
    return (countInvalid==0) ? true : false;
}

function getTabIndexById(tabsObj, tabId){
    var existingIndex = tabsObj.tabs('option','selected');
    var myIndex = tabsObj.tabs("select", tabId).tabs('option','selected');
    tabsObj.tabs("select", existingIndex);
    return myIndex;
}

$.fn.validateTab = function (tabsObj, tabIndex) {
    var isValid = true;
    var tabElement = $(this);

    tabElement.find("input, select, textarea").each(function () {
        //alert(this.getAttribute("id") );
        //alert(tabElement.validationEngine('validateField', "#"+this.getAttribute("id")) );
        if (tabElement.validationEngine('validateField', "#"+this.getAttribute("id"))) { //Invalid = true, Valid = false
            isValid = false;
            $(this).validationEngine("hide");
            //return false; //Break each loop
        }
       
    });

    return isValid;
}

/*
 * /End Jquery Tabs Function
 */


/*
 * Bind Json Data To Html Element By ID
 * @param responseText : Json Data
 */
function bindJsonToHtml(responseText, pageObj) {
    if (pageObj === 'undefined') {
        pageObj = $(document);
        alert("inundefined");
        alert(pageObj);
    }
    $.each(responseText, function(key, value) {               // Iterate over the JSON object.
        if (key == 'attr') {
            $.each(value, function() {
                var id;
                $.each(this, function(formKey, formValue) {
                    if (formKey == 'id') {
                        id = formValue;
                    } else if (formKey == 'mapAttr') {
                        pageObj.find(id).attr(formValue); //User .attr(map) To map all attribute then "map" = {key:value, key:value,...}
                    }
                });
            });
        } else if (key == 'removeAttr') {
            $.each(value, function(id, val) {
                pageObj.find(id).removeAttr(val);
            });
        } else if (key == 'html') {
            $.each(value, function(id, val) {
                pageObj.find(id).html(val);
            });
        } else if (key == 'text') {
            $.each(value, function(id, val) {
                pageObj.find(id).text(val);
            });
        } else if (key == 'val') {
            $.each(value, function(id, val) {
                pageObj.find(id).val(val);
            });
        } else if (key == 'addClass') {
            $.each(value, function(id, val) {
                pageObj.find(id).addClass(val);
            });
        } else if (key == 'removeClass') {
            $.each(value, function(id, val) {
                pageObj.find(id).removeClass(val);
            });
        } else if (key == 'toggleClass') {
            $.each(value, function(id, val) {
                pageObj.find(id).toggleClass(val);
            });
        } else if (key == 'showHide') {
            $.each(value, function(id, val) {
                if (val == "1") {
                    pageObj.find(id).show();
                } else if (val == "0") {
                    pageObj.find(id).hide();
                }

            });
        } else if (key == 'append') {
            $.each(value, function(id, val) {
                pageObj.find(id).append(val);
            });
        } else if (key == 'appendTo') {
            $.each(value, function(id, val) {
                pageObj.find(id).appendTo(val);
            });
        } else if (key == 'replaceWith') {
            $.each(value, function(id, val) {
                pageObj.find(id).replaceWith(val);
            });
        } else if (key == 'replaceAll') {
            $.each(value, function(id, val) {
                pageObj.find(id).replaceAll(val);
            });
        } else if (key == 'remove') {
            $.each(value, function(id, val) {
                pageObj.find(id).remove(val);
            });
        } else if (key == 'detach') {
            $.each(value, function(id, val) {
                pageObj.find(id).detach(val);
            });
        } else if (key == 'empty') {
            $.each(value, function(id, val) {
                pageObj.find(id).empty(val);
            });
        } else if (key == 'clone') {
            $.each(value, function(id, val) {
                pageObj.find(id).clone(val);
            });
        }
        /*
         * Json Format
         * {"ddl" :    [ #1
         *                      { #2
         *                          "id" :         "#ddlSelector",
         *                          "value" :      [
         *                                          { "Value 1" : "Text 1"},
         *                                           {"Value 2" : "Text 2"},
         *                                           {"Value 3" : "Text 3"}
         *                                         ],
         *                          "defaultType" :       "form" Or "search" Or Nothing,
         *                          "selectValue" :       "value to select"
         *                      },
         *                      {
         *                          .
         *                          .
         *                          .
         *                      }
         *                      .
         *                      .
         *                      .
         *             ]
         * }
         */
        else if (key == 'ddl') {
            $.each(value, function() { //For ArrayList #1
                var id;
                $.each(this, function(ddlOpt, ddlValue) { //For JsonObject #2
                    if (ddlOpt === 'id') {
                        id = pageObj.find(ddlValue);
                    } else if (ddlOpt === 'value') {
                        $.each(ddlValue, function() {
                        	$.each(this, function(optionValue, optionDisplay) {
                        		id.addOption(optionValue, optionDisplay, false);
                        	});
                            
                        });
                    } else if (ddlOpt === 'selectValue') {
                        id.selectOptions(ddlValue, true);
                    }
                });

            });
        } else if (key == 'ddlSelect') {
            $.each(value, function(id, val) {
                pageObj.find(id).selectOptions(val, true);
            });
        }
        /*
         * Json Format
         * {"ddlGroup" :    [ #1
         *                      { #2
         *                          "id" :          "#ddlSelector",
         *                          "defaultType" : "form" Or "search" Or Nothing,
         *                          "optGroup" :    { #3
         *                                              "group label value" :   { #4 //Actually we can send value as array list. But we send json obj cause addOption in jquery plugin
         *                                                                          "Value 1" : "Text 1",
         *                                                                          "Value 2" : "Text 2",
         *                                                                          "Value 3" : "Text 3"
         *                                                                      },
         *                                                                      .
         *                                                                      .
         *                                                                      .
         *                                          },
         *                          "selectValue" : "value to select"
         *                      },
         *                      {
         *                          .
         *                          .
         *                          .
         *                      }
         *                      .
         *                      .
         *                      .
         *                  ]
         *
         *
         * }
         */
        else if (key == 'ddlGroup') {
            $.each(value, function() { //For ArrayList #1
                var id;
                $.each(this, function(ddlOpt, ddlValue) { //For JsonObject #2
                    if (ddlOpt == 'id') {
                        id = pageObj.find(ddlValue);
                    } else if (ddlOpt == 'defaultType') {
                        if (ddlValue === 'form') {
                            id.append($("<option />").val("").text("Select"));
                        } else if (ddlValue === 'search') {
                            id.append($("<option />").val("").text("All"));
                        }
                    } else if (ddlOpt == 'optGroup') {
                        $.each(ddlValue, function(grpOpt, grpValue) { //For JsonObject #3
                            var optGroup = $("<optgroup></optgroup>").attr("label", grpOpt).appendTo(id);
                            $.each(grpValue, function(optVal, optText) { //For JsonObject #4
                                //alert(optText);
                                optGroup.append($("<option />").val(optVal).text(optText));
                            });
                        });
                    } else if (ddlOpt == 'selectValue') {
                        id.selectOptions(ddlValue, true);
                    }
                });

            });
        } else if (key == 'dialog') {
            $.each(value, function() {
                var id = "";
                var uiState = "";
                var uiIcon = "";
                var dialogTitle = "";
                $.each(this, function(msgKey, msgValue) {
                    if (msgKey == 'id') {
                        id = msgValue;
                        dialogTitle = "#ui-dialog-title-" + id;
                    } else if (msgKey == 'mapMsg') {
                        $.each(msgValue, function(msgCode, msgVar) {
                            if (msgCode == 'uiState') {
                                //ui-state à¸¡à¸µà¸”à¸±à¸‡à¸™à¸µà¹‰ highlight, error, error-text, disabled
                                //Set uiIcon By State : à¹€à¸£à¸²à¸ˆà¸°à¸�à¸³à¸«à¸™à¸” icon à¸•à¸²à¸¡ state à¹€à¸žà¸·à¹ˆà¸­à¸ˆà¸°à¹„à¸”à¹‰à¹ƒà¸Šà¹‰ icon à¹€à¸”à¸µà¸¢à¸§à¸�à¸±à¸™
                                if (msgVar == 'highlight') { //For Complete
                                    uiState = 'ui-state-highlight';
                                    uiIcon = '<span class="ui-icon ui-icon-circle-check" style="float:left;"></span>';
                                } else if (msgVar == 'error') { //For Error
                                    uiState = 'ui-state-error';
                                    uiIcon = '<span class="ui-icon ui-icon-circle-close" style="float:left;"></span>';
                                } else if (msgVar == 'focus') { //For Warning
                                    uiState = 'ui-state-highlight';
                                    uiIcon = '<span class="ui-icon ui-icon-alert" style="float:left;"></span>';
                                } else if (msgVar == 'default') { //For Confirm
                                    uiState = 'ui-state-highlight';
                                    uiIcon = '<span class="ui-icon ui-icon-help" style="float:left;"></span>';
                                }
                            } else if (msgCode == 'uiIcon') { //à¸–à¹‰à¸²à¸­à¸¢à¸²à¸�à¹€à¸›à¸¥à¸µà¹ˆà¸¢à¸™ icon à¹€à¸­à¸‡
                                uiIcon = '<span class="ui-icon ui-icon-' + msgVar + '" style="float:left;"></span>';
                            } else if (msgCode == 'msgTitle') {
//                                //à¹ƒà¸ªà¹ˆ title à¸�à¹ˆà¸­à¸™
//                                $(dialogTitle).text(constant[msgVar]); //constant[msgVar] à¸ˆà¸°à¸—à¸³à¹ƒà¸«à¹‰à¹€à¸›à¸¥à¸µà¹ˆà¸¢à¸™à¸ à¸²à¸©à¸²à¹„à¸”à¹‰
//                                //à¹ƒà¸ªà¹ˆ icon à¹�à¸¥à¸°à¹€à¸›à¸¥à¸µà¹ˆà¸¢à¸™ state
//                                $(dialogTitle).prepend(uiIcon).parent().addClass(uiState)
                            } else if (msgCode == 'msgContent') {
                                $(id).text([msgVar])
                            } else if (msgCode == 'isOpen') {
                                if (msgVar == '1') {
                                    $(id).dialog( "open" )
                                }
                            }

                            $(id).attr(msgValue);
                        });
                        
                    }
                });
            });
        }
    });
    updateForm();
}

/*
 * Show/Hide Loading
 */
function showLoading() {
    $("#loading").show();
}
function hideLoadings() {
    $("#loading").hide();
}




/*
 * Config Jquery Ajax
 */
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
$(document).ready(function() {
    /*$('#loading').ajaxStart(function() {
        //alert("ajaxStart");
        $(this).show();

    }).ajaxStop(function() {
        //alert("ajaxStop");

        $(this).hide();

    });*/
});












